package com.wing.cabinet.controller.app;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.entity.Cabinet;
import com.wing.cabinet.model.entity.CellInventoryInout;
import com.wing.cabinet.model.request.CellInventoryInoutForm;
import com.wing.cabinet.model.response.CellInventoryInoutVO;
import com.wing.cabinet.model.response.NeckNewExportVO;
import com.wing.cabinet.model.response.OldNeckNewExportVO;
import com.wing.cabinet.service.CellInventoryInoutService;
import com.wing.cabinet.utils.ExcelUtils;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.DepartmentVO;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-领新记录明细", tags = "#/cabinet/cellInventoryOut")
@RestController("appCellInventoryOutController")
@RequestMapping("cabinet/app/cellInventoryOut")
@RequiredArgsConstructor
public class CellInventoryOutController {

    private final CellInventoryInoutService cellInventoryInoutService;
    @Autowired
    private UserClient userClient;
    //查询所有售刀柜上货(上货主表无展示)/领取
    @ApiOperation(value = "领新记录明细", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "code", value = "存刀任务编号", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<CellInventoryInoutVO> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "desc") String order
            , String code
            , String cabCode
            , String skuCode
            , String skuCode4Detail
            , String startTime
            , String endTime
            , String deviceCode
            , String oldSpecCode
            , String mainCabCode
            , Cabinet.CabinetNature cabinetNature
            ,Long departmentId
            ,Long creatorId
            ,Long brandId
            ,Long categoryId
            ,Long productId
            ,Long roleId
            ,String skuCode4Query
            ,String deviceCode4Query
            ,Long packId
            ,String workOrderCode
            ,CellInventoryInout.BusinessType businessType
            ,String skuName
            ){

        Page<CellInventoryInout> pg = new Page<>(page, limit);
        Map queryParam=new HashMap();
        queryParam.put("sort",StrUtil.toUnderlineCase(sort));
        queryParam.put("order",order);
        queryParam.put("code",code);
        queryParam.put("cabCode",cabCode);
        queryParam.put("skuCode",skuCode);
//        queryParam.put("type",CellInventoryInout.Type.out.getValue());
        //queryParam.put("types",new Integer[]{CellInventoryInout.Type.out.getValue(),CellInventoryInout.Type.outByCabSpace.getValue()});
        queryParam.put("exportType",1);
        queryParam.put("skuCode4Detail",skuCode4Detail);
        queryParam.put("startCreateTime",startTime);
        queryParam.put("endCreateTime",endTime);
        queryParam.put("deviceCode",deviceCode);
        queryParam.put("oldSpecCode",oldSpecCode);
        queryParam.put("mainCabCode",mainCabCode);
        queryParam.put("skuName",skuName);
        if (cabinetNature!=null){
            queryParam.put("cabinetNature",cabinetNature.getValue());
        }
        if (businessType!=null){
            queryParam.put("businessType",businessType.getValue());
        }
        queryParam.put("enterpriseCode", JwtUtils.getEnterpriseCode());
        queryParam.put("departmentId",departmentId);
        queryParam.put("creator",creatorId);
        queryParam.put("brandId",brandId);
        queryParam.put("categoryId",categoryId);
        queryParam.put("productId",productId);
        queryParam.put("roleId",roleId);
        queryParam.put("oldSpecCode",oldSpecCode);
        queryParam.put("skuCode4Query",skuCode4Query);
        queryParam.put("deviceCode4Query",deviceCode4Query);
        queryParam.put("packId",packId);
        queryParam.put("workOrderCode",workOrderCode);

        IPage<CellInventoryInoutVO> list = cellInventoryInoutService.pageList(pg,queryParam);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加售刀柜上货(上货主表无展示)/领取", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(CellInventoryInoutForm.Add.class) CellInventoryInoutForm cellInventoryInoutForm) {
        if (cellInventoryInoutService.add(cellInventoryInoutForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改售刀柜上货(上货主表无展示)/领取", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(CellInventoryInoutForm.Update.class) CellInventoryInoutForm cellInventoryInoutForm) {
        CellInventoryInout cellInventoryInout = cellInventoryInoutService.getById(cellInventoryInoutForm.getId());
        if(cellInventoryInout == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CellInventoryInout.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(cellInventoryInoutForm, cellInventoryInout, copyOptions);
        if (cellInventoryInoutService.updateById(cellInventoryInout)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



@ApiOperation(value = "删除售刀柜上货(上货主表无展示)/领取", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cellInventoryInoutId", value = "售刀柜上货(上货主表无展示)/领取id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long cellInventoryInoutId) {
        if (cellInventoryInoutService.removeById(cellInventoryInoutId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "导出领新记录数据")
    @GetMapping("/export")
    public void export(HttpServletResponse response, String startCreateTime, String endCreateTime,@RequestParam(defaultValue = "1")Integer type){
        List<NeckNewExportVO> cellInventoryInoutVOList = new ArrayList<>();
        if ("".equals(startCreateTime) || "".equals(endCreateTime)){
            log.error("领取时间为空："+startCreateTime);
        }
        endCreateTime = endCreateTime+" 23:59:59";
        Map paramsMap = new HashMap();
        paramsMap.put("startCreateTime",startCreateTime);
        paramsMap.put("endCreateTime",endCreateTime);
//        paramsMap.put("type",CellInventoryInout.Type.out.getValue());
//        paramsMap.put("types",new Integer[]{CellInventoryInout.Type.out.getValue(),CellInventoryInout.Type.outByCabSpace.getValue()});
        paramsMap.put("exportType",type);

        cellInventoryInoutVOList = cellInventoryInoutService.ecxportList(paramsMap);
        for (NeckNewExportVO item : cellInventoryInoutVOList){
            JsonResult<DepartmentVO> jsonResult = userClient.getDepartmentVOById(item.getDepartmentId());
            JsonResult<DepartmentVO> jsonResult2 = userClient.getDepartmentVOById(item.getDeviceDepartmentId());
            item.setCostCenter(jsonResult.getData().getCostCenter());
            item.setDeviceDepartmentName(jsonResult2.getData().getName());
            if(StringUtils.isEmpty(item.getDeviceCode())){
                item.setDeviceCode("无");
            }
            if(StringUtils.isEmpty(item.getLifeUnitName())){
                item.setLifeUnitName("无");
            }
            if(StringUtils.isEmpty(item.getRemainingSettingTime())){
                item.setRemainingSettingTime("无");
            }
        }

        //导出
        ExcelUtils.export(response,"领新记录",cellInventoryInoutVOList, CellInventoryInoutVO.class);
    }
    @ApiOperation(value = "导出以旧换新领新")
    @GetMapping("/oldNewExport")
    public void oldNewExport(HttpServletResponse response, String startCreateTime, String endCreateTime,@RequestParam(defaultValue = "2")Integer type){
        List<OldNeckNewExportVO> cellInventoryInoutVOList = new ArrayList<>();
        if ("".equals(startCreateTime) || "".equals(endCreateTime)){
            log.error("领取时间为空："+startCreateTime);
        }
        endCreateTime = endCreateTime+" 23:59:59";
        Map paramsMap = new HashMap();
        paramsMap.put("startCreateTime",startCreateTime);
        paramsMap.put("endCreateTime",endCreateTime);
//        paramsMap.put("type",CellInventoryInout.Type.out.getValue());
        //paramsMap.put("types",new Integer[]{CellInventoryInout.Type.out.getValue(),CellInventoryInout.Type.outByCabSpace.getValue()});
        paramsMap.put("exportType",type);
        cellInventoryInoutVOList = cellInventoryInoutService.getOldNeckNewExportVOList(paramsMap);
        for(OldNeckNewExportVO item : cellInventoryInoutVOList){
            JsonResult<DepartmentVO> jsonResult = userClient.getDepartmentVOById(item.getDepartmentId());
            item.setCostCenter(jsonResult.getData().getCostCenter());
        }
        //导出
        ExcelUtils.export(response,"以旧换新领新",cellInventoryInoutVOList, OldNeckNewExportVO.class);
    }

    @ApiOperation(value = "生成领新账单", notes = "修改")
    @GetMapping("/createBill")
    public JsonResult createBill(Integer[] ids) {
        try {
            cellInventoryInoutService.syncBill(ids);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("生成领新账单接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }
    @PostMapping("/syncDjCellInventoryInoutData")
    public JsonResult syncDjCellInventoryInoutData() {
        try {
            cellInventoryInoutService.syncDjCellInventoryInoutData();
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("同步领新数据到东江系统接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }

}
